<template>
   <div class="coutract">
    <SearchBar @onSearch="handleSearch" @childFn="resetFormSearch">
      <SearchBarItem label="合同编号：" :labelLg="8">
        <Input type="text" v-model="searchDataModule.contractCode" placeholder="请输入" clearable />
      </SearchBarItem>
      <SearchBarItem label="所属机构：" :labelLg="8">
        <Input type="text" v-model="searchDataModule.organizationCode" placeholder="请输入" clearable />
      </SearchBarItem>
      <SearchBarItem label="商户名称：" :labelLg="8">
        <Input type="text" v-model="searchDataModule.merchantName" placeholder="请输入" clearable />
      </SearchBarItem>
      <SearchBarItem label="业务场景：" :labelLg="8">
        <Select v-model="searchDataModule.orderSource" placeholder="请选择" :clearable="isClear">
          <Option
            :value="item.key"
            v-for="(item, key) in businessSelect"
            :key="key"
          >{{item.value}}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="支付渠道：" :labelLg="8">
        <Select v-model="searchDataModule.payChannel" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in payChannelSelectList" :key="key">{{item.value}}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="发票类型：" :labelLg="8">
        <Select v-model="searchDataModule.invoiceType" placeholder="请选择" :clearable="isClear">
          <Option :value="item.key" v-for="(item, key) in invoiceSelect" :key="key">{{item.value}}</Option>
        </Select>
      </SearchBarItem>

       <SearchBarItem label="签订日期：" :labelLg="8">
        <DatePicker type="date" class="searchDate" ref="createDatePickerSign" transfer :value="searchDataModule.dataTimeSign" split-panels placeholder="请选择" @on-change="createTimeSign"></DatePicker>
      </SearchBarItem>
       <SearchBarItem label="开始-终止日期：" :labelLg="8">
        <DatePicker type="daterange" class="searchDate" ref="createDatePicker" transfer :value="searchDataModule.dataTime" split-panels placeholder="请选择" @on-change="createTime"></DatePicker>
      </SearchBarItem>
    </SearchBar>
    <RemoteTable
      :namespace="namespace"
      :columns="columns"
      @onSortChange="onSortChange"
      ref="tableData"
    >
      <template #extra>
        <Authc permissions="trade:common:config:contract:edit">
          <Button type="primary" @click="handleClick('add')">新增</Button>
        </Authc>
        <Authc permissions="trade:common:config:contract:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>

    </RemoteTable>

    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="title" width='800'>
       <Loading :loading="false">
        <Form
          ref="editFormData"
          :label-width="130"
          :model="editFormData"
          inline
          :rules="ruleValidate"
        >
          <FormItem label="合同编号：" prop="contractCode" style="width: 46%">
            <Input
              type="text"
              v-model="editFormData.contractCode"
              placeholder="请输入，字数不超过32"
              :maxlength="maxlength"
              clearable
            />
          </FormItem>
          <Row>
            <Col span="11">
              <FormItem label="所属机构：" prop="organizationCode" style="width: 100%">
                <Select
                  v-model="editFormData.organizationCode"
                  placeholder="请选择"
                  filterable
                  :label-in-value="true"
                  @on-change="bandleOrdanizationName"
                >
                  <Option
                    v-for="(item, index) in institutionalList"
                    :key="index"
                    :value="item.value"
                  >{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="机构编码：" style="width: 100%">
                <div>{{ editFormData.organizationCode }}</div>
              </FormItem>
            </Col>
          </Row>
          <Row v-if="editFormData.organizationCode ? true : false">
            <Col span="11">
              <FormItem label="商户名称：" prop="merchantCode" style="width: 100%">
                <Select
                  v-model="editFormData.merchantCode"
                  placeholder="请选择"
                  filterable
                  :label-in-value="true"
                  @on-change="bandleMerchantName"
                >
                  <Option
                    v-for="(item, index) in merchandList"
                    :key="index"
                    :value="item.value"
                  >{{ item.label }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="商户编码：" style="width: 100%">
                <div>{{ editFormData.merchantCode }}</div>
              </FormItem>
            </Col>
          </Row>
          <Row v-if="(editFormData.organizationCode && editFormData.merchantCode) ? true : false">
            <Col span="11">
              <FormItem label="支付渠道：" prop="payChannel" style="width: 100%">
                <Select
                  v-model="editFormData.payChannel"
                  placeholder="请选择"
                  @on-change="bandlePayChannel"
                >
                  <Option
                    v-for="(item, index) in payChannelSelect"
                    :key="index"
                    :value="item.key"
                  >{{ item.value }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="11" v-if="editFormData.payChannel">
              <FormItem label="商品数量：" style="width: 100%">
                <div>{{ editFormData.productQty }}</div>
              </FormItem>
            </Col>
          </Row>
          <FormItem label="业务场景：" prop="orderSource" style="width: 46%" v-if="editFormData.organizationCode ? true : false">
            <Select
              v-model="editFormData.orderSource"
              placeholder="请选择"
            >
              <Option
                v-for="(item, index) in businessSelect"
                :key="index"
                :value="item.key"
              >{{ item.value }}</Option>
            </Select>
          </FormItem>
          <Row>
            <Col span="11">
              <FormItem label="预付额度：" prop="amount" style="width: 100%">
                <Input
                  type="text"
                  v-model="editFormData.amount"
                  placeholder="请输入"
                  maxlength="12"
                  number
                  clearable
                >
                <span slot="append">元</span>
                </Input>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="发票类型：" prop="invoiceType" style="width: 100%">
                <Select
                  v-model="editFormData.invoiceType"
                  placeholder="请选择"
                >
                  <Option
                    v-for="(item, index) in invoiceSelect"
                    :key="index"
                    :value="item.key"
                  >{{ item.value }}</Option>
                </Select>

              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="11">
              <FormItem label="汇联易商户号：" style="width: 100%">
                <Input type="text" v-model="editFormData.huilianyi_no" placeholder="请输入,字数不超过32" :maxlength="maxlength" clearable />
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="税率：" prop="taxRate" style="width: 100%">
                <Input type="text" v-model="editFormData.taxRate" placeholder="请输入" maxlength="10" number clearable >
                  <span slot="append">%</span>
                </Input>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="11">
              <FormItem label="签订日期：" prop="contractDate" style="width: 100%">
                <DatePicker type="date" v-model="editFormData.contractDate" placement="top" transfer format="yyyy-MM-dd" @on-change="setContractDate" placeholder="选择日期区间" clearable></DatePicker>
              </FormItem>
            </Col>
            <Col span="11">
                <FormItem label="开始-终止日期：" prop="validTime" style="width: 100%">
                  <DatePicker v-model="editFormData.validTime" type="daterange" transfer format="yyyy-MM-dd" placeholder="选择日期区间" @on-change="setDateRange" clearable></DatePicker>
                </FormItem>
            </Col>
          </Row>
        </Form>
      </Loading>
      <div slot="footer">
        <Button type="primary" @click="handleSubmit('editFormData')">确定</Button>
        <Button @click="handleReset('editFormData')" style="margin-left: 8px">返回</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  Button,
  Input,
  Modal,
  Message,
  Col,
  Row,
  Form,
  FormItem,
  DatePicker,
  Select,
  Option,
  Card,
  Radio,
  RadioGroup
} from "view-design";
import Loading from "@/components/Loading";
import RemoteTable from "@/components/RemoteTable";
import RemoteSelect from "@/components/RemoteSelect";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../Module/configContractModule";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import util from "@/utils/util";
import appService from "@/utils/appService";

export default {
  name: "tables_page11",
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Radio,
    RadioGroup
  },
  data() {
    return {
      maxlength: 32,
      title: "",
      isShow: false,
      namespace: namespace,
      loading: true,
      isClear: true,
      editFormData: {
        validTime: []
      },
      searchDataModule: {},
      ruleValidate: {
        contractCode: [{ required: true, message: '请填写', trigger: 'blur' }], // 合同编号
        organizationCode: [{ required: true, message: '请选择', trigger: 'change' }], // 所属机构
        merchantCode: [{ required: true, message: '请选择', trigger: 'change' }], // 商户名称
        payChannel: [{ required: true, message: '请选择', trigger: 'change' }], // 支付渠道
        orderSource: [{ required: true, message: '请选择', trigger: 'change' }], // 业务场景
        invoiceType: [{ required: true, message: '请填写', trigger: 'change' }], // 发票类型
        taxRate: [{ required: true, type:'number', validator: this.validateNum, trigger: 'blur' }],  // 税率

        amount: [{ required: true, type: 'number', message: '请填写数字', trigger: 'blur' }], // 预付额度
        huilianyi_no: [{ required: true, message: '请填写', trigger: 'blur' }], // 汇联易商户号
        validTime: [{ required: true, validator: this.validateDaterange, trigger: "change" }], // 开始 - 结束时间
        contractDate: [{ required: true, validator: this.validateDaterange, trigger: "change" }], // 合同签订日期
      },
      columns: [
        {
          type: "index",
          title: "序号",
          minWidth: 80,
          align: "center",
          // fixed: "left"
        },
        {
          title: "合同编号",
          key: "contractCode",
          align: "center",
          minWidth: 150
        },
        {
          title: "所属机构",
          key: "organizationName",
          align: "center",
          minWidth: 210
        },
        {
          title: "商户名称",
          key: "merchantName",
          align: "center",
          minWidth: 210
        },
        {
          title: "产品数量",
          key: "productQty",
          align: "center",
          minWidth: 100
        },
        {
          title: "业务场景",
          key: "orderSourceCn",
          align: "center",
          minWidth: 100
        },
        {
          title: "支付渠道",
          key: "payChannelCn",
          align: "center",
          minWidth: 140
        },
        {
          title: "预付额度(元)",
          key: "amount",
          align: "center",
          minWidth: 120,
          render: (h, params) => {
            let item = params.row.amount;
            if (item) {
              return h('span', util.toMoney(item))
            } else {
              return h('span', '0.00')
            }
          }
        },
        {
          title: "发票类型",
          key: "invoiceTypeCn",
          align: "center",
          minWidth: 150
        },
        {
          title: "税率",
          key: "taxRate",
          align: "center",
          minWidth: 100,
          render: (h, params) => {
            return h('span', params.row.taxRate + '%')
          }
        },
        {
          title: "签订日期",
          key: "contract_sign_date",
          align: "center",
          minWidth: 100
        },
        {
          title: "开始日期",
          key: "contractStartDate",
          align: "center",
          minWidth: 150
        },
        {
          title: "终止日期",
          key: "contractEndDate",
          align: "center",
          minWidth: 150
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          // fixed: "right",
          permissions: ["trade:settlement:manager"],
          minWidth: 150,
          render: function(h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      addType: false,
      payChannelSelect: [], // 渠道类型
      payChannelSelectList: [], /** 搜索框选择渠道 */
      businessSelect: [], // 业务场景
      invoiceSelect: [], // 发票类型
      merchandList: [], // 商户list
      institutionalList: [], // 组织机构
      merchandCode: '',  /** 商户编码 */
      payChannelCode: '' /** 支付渠道 */
    };
  },
  created() {
    this.getMerchantSearchKey(); /** 字典 */
    this.getInstitutionalList(); /** 列表 */
    this.getAllMerchandChannel(); /** 搜搜框全部渠道 */
  },
  methods: {
    /**  */
    validateNum (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入数字'));
      } else if (!Number.isInteger(+value)) {
        callback(new Error('请输入数字'));
      } else if (value > 100) {
        callback(new Error('税率不能大于100'))
      }
      callback()
    },
    /** 表单验证 **/
    validateSequence(rule, value, callback){
      if (value === '') {
            callback(new Error('请输入'));
      } else if (!Number.isInteger(+value)) {
            callback(new Error('输入数字'));
      } else {
            callback();
      }
    },
    /** 表单 日期验证 **/
    validateDaterange(rule, value, callback){
      if (!value) {
        callback(new Error("日期不能为空"));
      } else {
        callback();
      }
    },
    // 签订日期
    setContractDate (val) {
      this.editFormData.contract_sign_date = val;
    },
    // 开始日期 - 结束时间
		setDateRange (val) {
      this.editFormData.validTime = val;
      this.editFormData.contractStartDate = val[0];
      this.editFormData.contractEndDate = val[1];
    },

		createTime (date, type) {
      this.searchDataModule.contractStartDate = date ? date[0] : '';
      this.searchDataModule.contractEndDate = date ? date[1] : '';
    },

    createTimeSign (date, type) {
      this.searchDataModule.contract_sign_date = date;
    },

    // 清空事件；
    resetFormSearch() {
      this.$set(this.searchDataModule, 'contractCode', '');
      this.$set(this.searchDataModule, 'organizationCode', '');
      this.$set(this.searchDataModule, 'merchantName', '');
      this.$set(this.searchDataModule, 'payChannel', '');
      this.$set(this.searchDataModule, 'orderSource', '');
      this.$set(this.searchDataModule, 'invoiceType', '');
      // // 清空时间选择
      this.$refs["createDatePicker"].handleClear();
      this.$refs["createDatePickerSign"].handleClear();
    },
    handleClear () {
      // this.$set(this.searchDataModule, 'validTime', []);
    },

    // 字典
    getMerchantSearchKey () {
      this.$store.dispatch(`${namespace}/getMerchantSearchKey`).then((res)=>{
        if (res.data.ret === 0) {
          let data = res.data.data;
          // this.payChannelSelect = data.payChannel // 渠道类型
          this.businessSelect = data.orderSource // 业务场景
          this.invoiceSelect = data.invoiceType // 发票类型
        }
      })
    },

    // 商户列表list
    async getMerchandListData () {
      console.log('进来了 ')
      try {
        let params = {
          organizationCode: this.editFormData.organizationCode
        }
        let res = await this.$store.dispatch(`${namespace}/getMerchandList`, params);
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.merchandList = data.length ? data.map(({ merchantName, merchantCode }) => {
            return {
              label: merchantName,
              value: merchantCode
            }
          }) : []
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },
    // 搜索全部渠道
    async getAllMerchandChannel () {
      try {
        let params = {
          currentPage: 1,
          pageSize: 9999
        }
        let res = await this.$store.dispatch(`${namespace}/AllMerchandChannel`, params);
        if (res.data.ret === 0) {
          let data = res.data.data.list;
          this.payChannelSelectList = data.map(({ paymentChannelCode, paymentChannelName }) => {
            return {
              value: paymentChannelName,
              key: paymentChannelCode
            }
          })
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    // 编辑-商户列表- 对应的渠道
    async getMerchandChannel () {
      try {
        let params = {
          merchantCode: this.merchandCode
        }
        let res = await this.$store.dispatch(`${namespace}/getMerchandList`, params);
        if (res.data.ret === 0) {
          let data = res.data.data[0].channelList;
          this.payChannelSelect = data != '' ? data.map(({ paymentChannelCode, paymentChannelName }) => {
            return {
              value: paymentChannelName,
              key: paymentChannelCode
            }
          }) : []
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    // 编辑 - 组织列表list
    getInstitutionalList () {
      let params = {
        currentPage: 1,
        pageSize: 10
      }
      this.$store.dispatch(`${namespace}/getInstitutionalList`, params).then((res)=>{
        if (res.data.ret === 0) {
          let data = res.data.data.list.map(({ organizationName, organizationCode }) => {
            return {
              label: organizationName,
              value: organizationCode
            }
          })
          this.institutionalList = data;
        }
      })
    },

    // 获取商品数量
    async getMerchandNum () {
      let params = {
        merchantCode: this.merchandCode,
        paymentChannel: this.payChannelCode
      }
      let res = await this.$store.dispatch(`${namespace}/getMerchandNum`, params);
      if (res && res.data.ret === 0) {
        this.$set(this.editFormData, 'productQty', res.data.data)
      }
    },

    // 导出
    async exportExcel (params) {
      try {
        let res = await this.$store.dispatch(`${namespace}/exportExcel`, this.searchDataModule);

        util.exportExcle(res, '商户合同管理表');
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    handleReset (formName) {
      this.isShow = false;
      this.$refs[formName].resetFields();
    },
    handleSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.addType) {
            this.$store.dispatch(`${namespace}/save`, this.editFormData).then(res => {
              if( res.ret === 0 ){
                this.$Message.success({
                  content: res.msg
                });
                // this.editFormData = {};
                this.isShow = false;
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.warning({
                  content: res.msg
                })
              }
            });
          } else {
            this.$store.dispatch(`${namespace}/localUpdate`, this.editFormData).then(res => {
              if( res.ret === 0 ){
                this.$Message.success({
                  content: res.msg
                });
                // this.editFormData = {};
                this.isShow = false;
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.warning({
                  content: res.msg
                });
              }
            })
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    handleClick(type) {
      switch (type) {
        case "add":
          this.editFormData = {};
          this.isShow = true;
          this.addType = false;
          this.title = "新增商户合同";
          this.resetFormAll();
          break;
        case "edit":
          break;
        case "delete":
          break;
        default:
      }
    },
    resetFormAll () {
      this.$refs['editFormData'].resetFields()
    },
    handleSearch() {
      this.$store.dispatch(`${namespace}/query`, this.searchDataModule);
    },
    onSortChange(sort) {
      if (sort.order === "normal") {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + " " + sort.order];
      }
      this.handleSearch();
    },

    /** 机构 */
    bandleOrdanizationName (val) {
      this.editFormData.organizationName = val ? val.label : '';
      this.$set(this.editFormData, 'merchantName', '')
      this.resatMerchant(); /** 重置商户 */
      this.getMerchandListData(); /** 获取商户名称 */
    },

    /** 商户 */
    bandleMerchantName (val) {
      this.merchandCode = val ? val.value : '';
      this.editFormData.merchantName = val ? val.label : '';
      this.resetChannel(); /** 重置-渠道 */
      this.getMerchandChannel(); /** 获取商户对应的渠道 */
    },

    /** 渠道 */
    bandlePayChannel (val) {
      this.payChannelCode = val;
      this.getMerchandNum(); /** 查询商品数量 */
    },

    /** 商户重置 - 重置渠道 */
    resetChannel () {
      this.$set(this.editFormData, 'payChannel', '')
      this.$set(this.editFormData, 'productQty', '')
      this.$refs['editFormData'].fields.forEach(function (e) {
        if (e.prop == 'payChannel' || e.prop == 'productQty') e.resetField();
      })
    },

    /** 机构切换-重置相关联的 */
    resatMerchant () {
      this.$set(this.editFormData, 'merchantName', '')
      this.$set(this.editFormData, 'merchantCode', '')
      this.$set(this.editFormData, 'payChannel', '')
      this.$set(this.editFormData, 'productQty', '')
      this.$refs['editFormData'].fields.forEach(function (e) {
        if (e.prop == 'merchantName' || e.prop == 'merchantCode' || e.prop == 'payChannel' || e.prop == 'productQty') e.resetField();
      })
    }
  },

   mounted() {
    this.$bus.$on("actionType", data => {
      let id = data.id;
      if (data.type === "edit") {
        let organizationCode = data.rowData.organizationCode;
        let merchantCode = data.rowData.merchantCode;
        this.title = '编辑商户合同';
        this.isShow = true;
        this.addType = true;
        this.resetFormAll();
        this.$store.dispatch(`${namespace}/getDetail`, id).then(res => {
          if (res.ret === 0) {
            this.editFormData = res.data;
            this.editFormData.validTime = [res.data.contractStartDate, res.data.contractEndDate];
            this.editFormData.contractDate = res.data.contract_sign_date
          }
        });

        if (organizationCode) {

          // 获取商户
          let params = {
            organizationCode: organizationCode
          }
          this.$store.dispatch(`${namespace}/getMerchandList`, params).then(res => {
            if (res.data.ret === 0) {
              let dataList = res.data.data;
              if (dataList.length > 0) {
                this.merchandList = dataList.map(({ merchantCode, merchantName }) => ({
                  value: merchantCode,
                  label: merchantName
                }))
              } else {
                this.merchandList = []
              }
            }
          })
        }

        // // 获取渠道
        let paramss = {
          merchantCode: merchantCode
        }
        this.$store.dispatch(`${namespace}/getMerchandList`, paramss).then(resss => {
          if (resss.data.ret === 0) {
            let dataItem = resss.data.data[0].channelList;
            if (dataItem.length > 0) {
              this.payChannelSelect = dataItem.map(({ paymentChannelCode, paymentChannelName }) => {
                return {
                  key: paymentChannelCode,
                  value: paymentChannelName
                }
              })
            } else {
              this.payChannelSelect = []
            }
          }
        })

      }else if (data.type === "cancel") {
        Modal.confirm({
          render: (h, params) => {
            return h("div", [
              h(
                "div",
                {
                  class: "selfConfirm"
                },
                "是否确认删除?"
              )
            ]);
          },
          onOk: () => {
            return this.$store.dispatch(`${namespace}/delete`, id).then(e => {
              if( e.ret === 0 ){
                this.$Message.success(e.msg);
                this.$store.dispatch(`${namespace}/query`);
              } else {
                this.$Message.warning(e.msg);
              }
            });
          }
        });
      }
    });
  },
  beforeDestroy() {
    this.$bus.$off('actionType');
  }
};
</script>

<style lang="less" scoped>
.coutract {
  .searchDate {
    width: 100%;
  }
}
</style>
